var mWhsCode = $('#m_WhsCode'),
    mArea = $('#m_Area'),
    mCode = $('#m_Code'),
    mName = $('#m_Name'),
    mType = $('#m_Type'),
    tree =  $('#jstree_folders'),
    _grid = $('#jgTable');

var Data = [],
    Code = '',
    Name = '',
    level1 = '',
    Father = 'Init';

var _postData = {
    Method: 'Q',
    Content:{
        WhsCode: '',
        Area: '',
        SearchText: ''
    }
};
for(i in postData){
    _postData[i] = postData[i];
}

gridWidth = $('.u_block_content');

$(function(){
    treeInit();
    requestAjax01();
    _gridInit();
    $('li[data-opt="new1"]').on('click', nodeNew1);
    $('li[data-opt="new2"]').on('click', nodeNew2);
    $('li[data-opt="new3"]').on('click', nodeNew3);
    tree.on("changed.jstree", function (e, data) {
        //console.log(data.action) //deselect_all,select_node,ready
        if (data.action === 'select_node') {
            //console.log('选中节点')
            Code = data.node.li_attr.Code;
            Name = data.node.li_attr.Name;
            level1 = data.node.li_attr.level1;
            Father = data.node.li_attr.Father;
            if(level1 == '1'){
                _postData = {
                    Content:{
                        WhsCode: Code,
                        Area: '',
                        SearchText: '' 
                    }
                }
            } else if (level1 == '2') {
                _postData = {
                    Content:{
                        WhsCode: Father,
                        Area: Code,
                        SearchText: '' 
                    }
                }
            }
            _grid.trigger("reloadGrid");
        }else if(data.action === 'deselect_all') {
            //console.log('加载完成')
            tree.jstree('open_all');
            //var Selected = $('li[code="CA0265"]');
            //Selected.find('>a').trigger('click');
        }
    });
    $('.modal-data').draggable();
});

function context_menu() {
    var items = {
        'Edit': {
            'label': '重新编辑',
            'action': nodeEdit
        },
        'Delete': {
            'label': '删除',
            'action': nodeDelete
        },
        'New1': {
            'label': '新建仓库',
            'action': nodeNew1
        },
        'New2': {
            'label': '新建库区',
            'action': nodeNew2
        },
        'New3': {
            'label': '新建库位',
            'action': nodeNew3
        }
    };
    return items;    
}

function requestAjax01() {  //MDM002703
    $.ajax({
        async: false,
        type: "post",
        url: mdmPath + "/MDM0027/MDM002703",
        data: {
            Method: 'Q',
            Tonken: postData.Tonken,
            UserCode: postData.UserCode,
            BrowserID: postData.BrowserID,
            Source: postData.Source
        },
        dataType: "json",
        success: function(re) {
            loadAjax01(re);
        }
    });    
}
function loadAjax01(re) {
    re.Status == -999 && alert_QX($('body'),re.Message);
    Data = re.Content;
    if(Data.length > 0) {
        treeRefresh();
    }else {
        firstNodeNew();
    }
}

function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_edit" title="编辑"><i class="fa fa-pencil"></i></a>'+
            '&nbsp;<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}
function _gridInit(){
    var _gridData = Object.create(gridData);
    _gridData.url = mdmPath + '/MDM0028/MDM002803';
    _gridData.colModel = [
        {label:'代码', name:'Code'},
        {label:'名称', name:'Name'},
        {label:'仓库', name:'WhsCode'},
        {label:'库区', name:'Area'},
        {label:'操作', name:'Options', align:'center', formatter: alarmFormatter, sortable:false}
    ];
    _gridData.sortname = 'Code';
    _gridData.beforeRequest = function(){
        _gridData.grid.jqGrid("setGridParam", {
            postData : _postData,
        });
    };
    _gridData.loadComplete = function(xhr){
        xhr.Status == -999 && alert_situ($('.u_row').find('.u_table_container'),re.Message);
        $('a[opt-data="jgTable_edit"]').unbind('click').bind('click', function(){
            var rowId = $(this).parent().parent()[0].id;
            editCode(rowId);
        });
        $('a[opt-data="jgTable_delete"]').unbind('click').bind('click', function(){
            var rowId = $(this).parent().parent()[0].id;
            deleteCode(rowId);
        });
    };
    gridInit(_gridData);
    gridSearch = _postData;
}

//Options 
function nodeNew1(){    //MDM0027/MDM002701
    mWhsCode.parent().parent().addClass('hidden');
    mArea.parent().parent().addClass('hidden');
    mType.parent().parent().removeClass('hidden');
    mCode.val('').attr('disabled', false);
    mName.val('');
    $('.modal-overlay').removeClass('hidden');
    $('#submitBtn').unbind('click').bind('click', function(){
        var new1Data = {
            Method: 'A',
            Content: {
                Code: mCode.val(),
                Name: mName.val(),
                Type: mType.val()
            }
        }
        for(i in postData) {
            new1Data[i] = postData[i]
        }
        $.ajax({
            type: 'post',
            url: mdmPath + '/MDM0027/MDM002701',
            data: new1Data,
            dataType: 'json',
            success: function(re) {
                if(re.Status==200) {
                    myAlert('创建成功');
                    requestAjax01();
                    $('.modal-overlay').addClass('hidden');
                } else {
                    myAlert(re.Message);
                }
            }
        });
    });
}
function nodeNew2(){    //MDM0049/MDM004901
    mWhsCode.parent().parent().removeClass('hidden');
    mArea.parent().parent().addClass('hidden');
    mType.parent().parent().addClass('hidden');
    mCode.val('').attr('disabled', false);
    mName.val('');
    if(Father != 'Init') {
        if(Father == ''){
            mWhsCode.val(Code);
        }else {
            mWhsCode.val(Father);
        }
        $('.modal-overlay').removeClass('hidden');
        $('#submitBtn').unbind('click').bind('click', function(){
            var new2Data = {
                Method: 'A',
                Content: {
                    Code: mCode.val(),
                    Name: mName.val(),
                    WhsCode: mWhsCode.val()
                }
            }
            for(i in postData) {
                new2Data[i] = postData[i]
            }
            $.ajax({
                type: 'post',
                url: mdmPath + '/MDM0049/MDM004901',
                data: new2Data,
                dataType: 'json',
                success: function(re) {
                    if(re.Status==200) {
                        myAlert('创建成功');
                        requestAjax01();
                        $('.modal-overlay').addClass('hidden');
                    } else {
                        myAlert(re.Message);
                    }
                }
            });
        });        
    }else {
        myAlert('请选择仓库');
    }
}
function nodeNew3(){    //MDM0028/MDM002801
    mWhsCode.parent().parent().removeClass('hidden');
    mArea.parent().parent().removeClass('hidden');
    mType.parent().parent().addClass('hidden');
    mCode.val('').attr('disabled', false);
    mName.val('');
    if(Father != 'Init'&&Father != ''){
        mWhsCode.val(Father);
        mArea.val(Code);
        $('.modal-overlay').removeClass('hidden');
        $('#submitBtn').unbind('click').bind('click', function(){
            var new3Data = {
                Method: 'A',
                Content: {
                    Code: mCode.val(),
                    Name: mName.val(),
                    WhsCode: mWhsCode.val(),
                    Area: mArea.val()
                }
            }
            for(i in postData) {
                new3Data[i] = postData[i]
            }
            $.ajax({
                type: 'post',
                url: mdmPath + '/MDM0028/MDM002801',
                data: new3Data,
                dataType: 'json',
                success: function(re) {
                    if(re.Status==200) {
                        myAlert('创建成功');
                        _grid.trigger("reloadGrid");
                        $('.modal-overlay').addClass('hidden');
                    } else {
                        myAlert(re.Message);
                    }
                }
            });
        });
    }else {
        myAlert('请选择库区');
    }
}
function firstNodeNew(){
    $('.u_fixed_row').append('<a href="javascript:0" class="firstBtn">开始创建第一条数据</a>');
    $('.firstBtn').on('click', function(){
        mPCode.val(0);
        mLevel.val(1);
        mCode.val('').attr('disabled', false);
        mName.val('');
        $('.modal-overlay').removeClass('hidden');
            $('#submitBtn').unbind('click').bind('click', function(){
            var _postData = {
                Method: 'A'
            }
            requestAjax03(_postData);
            $('.firstBtn').remove();
        })
    })
}
function nodeEdit(){
    console.log(level1)
    console.log(Father)
    console.log(Code)
    switch(level1){
        case 1:
            mWhsCode.parent().parent().addClass('hidden');
            mArea.parent().parent().addClass('hidden');
            mType.parent().parent().removeClass('hidden');
            mCode.val(Code).attr('disabled', true);
            mName.val('');
            $('.modal-overlay').removeClass('hidden');
            $('#submitBtn').unbind('click').bind('click', function(){
                var new1Data = {
                    Method: 'U',
                    Content: {
                        Code: mCode.val(),
                        Name: mName.val(),
                        Type: mType.val()
                    }
                }
                for(i in postData) {
                    new1Data[i] = postData[i]
                }
                $.ajax({
                    type: 'post',
                    url: mdmPath + '/MDM0027/MDM002701',
                    data: new1Data,
                    dataType: 'json',
                    success: function(re) {
                        if(re.Status==200) {
                            myAlert('修改成功');
                            requestAjax01();
                            $('.modal-overlay').addClass('hidden');
                        } else {
                            myAlert(re.Message);
                        }
                    }
                });
            });
        break;
        case 2:
            mWhsCode.parent().parent().removeClass('hidden');
            mArea.parent().parent().addClass('hidden');
            mType.parent().parent().addClass('hidden');
            mCode.val(Code).attr('disabled', true);
            mName.val('');
            if(Father != 'Init') {
                if(Father == ''){
                    mWhsCode.val(Code);
                }else {
                    mWhsCode.val(Father);
                }
                $('.modal-overlay').removeClass('hidden');
                $('#submitBtn').unbind('click').bind('click', function(){
                    var new2Data = {
                        Method: 'U',
                        Content: {
                            Code: mCode.val(),
                            Name: mName.val(),
                            WhsCode: mWhsCode.val()
                        }
                    }
                    for(i in postData) {
                        new2Data[i] = postData[i]
                    }
                    $.ajax({
                        type: 'post',
                        url: mdmPath + '/MDM0049/MDM004901',
                        data: new2Data,
                        dataType: 'json',
                        success: function(re) {
                            if(re.Status==200) {
                                myAlert('修改成功');
                                requestAjax01();
                                $('.modal-overlay').addClass('hidden');
                            } else {
                                myAlert(re.Message);
                            }
                        }
                    });
                });        
            }else {
                myAlert('请选择仓库');
            }
        break;
    }
}
function nodeDelete(){
    myAlert('暂无删除功能')
}

function editCode(rowId){
    if(rowId) {
        mType.parent().parent().addClass('hidden'); 
        var rowData = _grid.jqGrid('getRowData', rowId);
        mWhsCode.val(rowData.WhsCode).parent().parent().removeClass('hidden');
        mArea.val(rowData.Area).parent().parent().removeClass('hidden');
        mCode.val(rowData.Code).attr('disabled', true);
        mName.val(rowData.Name);
        $('.modal-overlay').removeClass('hidden');
        $('#submitBtn').unbind('click').bind('click', function(){
            var new3Data = {
                Method: 'U',
                Content: {
                    Code: mCode.val(),
                    Name: mName.val(),
                    WhsCode: mWhsCode.val(),
                    Area: mArea.val()
                }
            }
            for(i in postData) {
                new3Data[i] = postData[i]
            }
            $.ajax({
                type: 'post',
                url: mdmPath + '/MDM0028/MDM002801',
                data: new3Data,
                dataType: 'json',
                success: function(re) {
                    if(re.Status==200) {
                        myAlert('修改成功');
                        _grid.trigger("reloadGrid");
                        $('.modal-overlay').addClass('hidden');
                    } else {
                        myAlert(re.Message);
                    }
                }
            });
        });
    }else {
        myAlert('请选择您要编辑的库位');
    }
}
function deleteCode(){
    myAlert('暂无删除功能')
}